package logic

import (
	"context"
	"encoding/json"
	"home-manage/cache"
	"home-manage/model"
	"time"

	"home-manage/homerpc/homerpc"
	"home-manage/homerpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ConsultationListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewConsultationListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ConsultationListLogic {
	return &ConsultationListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ConsultationListLogic) ConsultationList(in *homerpc.ConsultationListRequest) (*homerpc.ConsultationListResponse, error) {
	// todo: add your logic here and delete this line

	offset := (in.Page - 1) * in.Size
	var consultations []model.Consultation

	result, _ := cache.Rdb.Get(l.ctx, "List").Result()
	if result == "" {
		model.DB.Debug().Offset(int(offset)).Limit(int(in.Size)).Find(&consultations)

		marshal, _ := json.Marshal(consultations)

		cache.Rdb.Set(l.ctx, "List", marshal, time.Minute*15)
	} else {
		json.Unmarshal([]byte(result), &consultations)
	}

	var consultationList []*homerpc.ConsultationList

	for _, consultation := range consultations {

		list := homerpc.ConsultationList{
			UserId:  int64(consultation.UserId),
			HouseId: int64(consultation.HouseId),
			Content: consultation.Content,
		}
		consultationList = append(consultationList, &list)
	}
	return &homerpc.ConsultationListResponse{
		List: consultationList,
	}, nil
}
